package com.ruibang.glass.produce.listener.event;

import com.alibaba.fastjson.JSON;
import com.ruibang.glass.produce.constant.Constants;
import com.ruibang.glass.produce.domain.event.MonitorCacheEvent;
import com.ruibang.glass.produce.domain.resp.Monitor;
//import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author: songJinKang
 * @CreateTime: 2023-11-21  09:55
 * @Description: TODO
 * @Version: 1.0
 */

@Slf4j
@Component
public class MonitorRealTimeEvent {

//    @Autowired
//    private RedisSingleService redisService;

    @Autowired
    private RedisSingleService redisService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Async
    @TransactionalEventListener(classes = MonitorCacheEvent.class, fallbackExecution = true)
    public void monitorCache(MonitorCacheEvent event) {
        List<Monitor> monitors = event.getMonitors();
        if (CollectionUtils.isNotEmpty(monitors)) {

            for (Monitor monitor : monitors) {
                //监测点ID对应关系
                redisService.hset(Constants.MONITOR_ID_REAL_TIME_CACHE_KEY, monitor.getMonitorId(), JSON.toJSONString(monitor));
            }

            //设备对应关系
            Map<String, List<Monitor>> monitorMap = monitors.stream().collect(Collectors.groupingBy(Monitor::getDeviceId));
            monitorMap.forEach((k, v) -> {
                String key = String.format(Constants.DEVICE_MAPPING_MONITOR_CACHE, k);
                for (Monitor monitor : v) {
                    redisTemplate.opsForHash().put(key, monitor.getMonitorId(), JSON.toJSONString(monitor));
                }
            });
        }
    }


}
